<template>
  <div>
<!--    <el-form-item label="商品名称">-->
<!--      <zSelect :value.sync="query.goodsId" url="api/dropDown/basGoodsList" style="width:  100%" @change="getHistory"/>-->
<!--    </el-form-item>-->


    <div>
      <el-form ref="form" :model="form" label-width="80px">
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商品">
            <el-input v-model="query.goodsKeyword" placeholder="输入关键字搜索"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商品分类">
            <treeselect
              multiple
              v-model="goodsTypeIds"
              :options="typeList"
              placeholder="选择商品分类"
              style="width: 100%"
              :normalizer="normalizer"
              @select="onGoodsTypeNode"
            >
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商品品牌">
            <zSelect multiple :value.sync="goodsBrandIds" url="api/dropDown/basGoodsBrandList" style="width:  100%;">
            </zSelect>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="年份">
            <el-select v-model="query.year" placeholder="请选择年份">
              <el-option
                v-for="item in years"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <div style="width: 100%" class="flex flex-reverse">
            <el-button style="margin-left: 100px" type="primary" @click="getHistory"  round>搜索</el-button>
          </div>
        </el-col>
      </el-row>
      </el-form>
    </div>
    <el-table ref="table" stripe border
              :data="detailList"
              size="small"
              style="width: 100%;"
              height="300"
              :show-summary="true"
              :summary-method="sumRow"
              @selection-change="selectionChangeHandler">
<!--      <el-table-column  type="selection" width="60"/>-->
      <el-table-column  type="index" width="60" label="序号"/>
      <el-table-column  prop="busDate" label="业务日期"/>
      <el-table-column  prop="orderCode" label="订单编码"/>
      <el-table-column  prop="orderType" label="单据类型">
              <template slot-scope="scope">
                {{ scope.row.orderType === '1'?'销售单':'退货单' }}
              </template>
            </el-table-column>
      <el-table-column  prop="goodsName" label="商品名称"/>
      <el-table-column  prop="goodsCode" label="商品编码"/>
      <el-table-column  prop="goodsTagName" label="商品类型"/>
      <el-table-column  prop="barcode" label="条形码"/>
      <el-table-column  prop="boxUnitCount" label="辅数量">
        <template slot-scope="{row}">
          {{ row.boxNum }}{{ row.boxUnitName }}{{ row.mainNum?row.mainNum:0 }}{{ row.mainUnitName }}
        </template>
      </el-table-column>
      <el-table-column  prop="goodsCount" label="数量"/>
      <el-table-column  prop="taxPrice" label="单价"/>
      <el-table-column  prop="taxBoxPrice" label="箱价"/>
      <el-table-column  prop="taxAmount" label="金额"/>
      <el-table-column  prop="promotionName" v-if="historyType === 'SAVE'" label="促销"/>
      <el-table-column  prop="goodsRemark" label="备注"/>
      <!--      <el-table-column  prop="type" label="销售单类型">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ dict.label.t_sales_order_type[scope.row.type] }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->

    </el-table>

    <el-pagination
      :current-page="query.page"
      :page-size="query.size"
      layout="total, prev, pager, next"
      :total="total"
      :pager-count="5"
      @current-change="currentcurrent"
    />
<!--    <div class="cu-footer">-->
<!--      <el-button type="text" @click="closedDialog()">取消</el-button>-->
<!--      <el-button type="primary" @click="submitCU">确认</el-button>-->
<!--    </div>-->
  </div>
</template>

<script>
import {getSaleOrderHistoryDetail} from "@/api/erp/salesOrderDetail";
import {getSalesHistory,getBuyHistory, newSalesHistory} from "@/api/erp/basGoods";
import Treeselect from '@riophae/vue-treeselect'
import {getTypeList} from "@/api/erp/basGoodsType";
import { getDict } from '../../../api/erp/tableColumnConfig'


export default {
  name: "history",
  props: {
    data: Object,
    detailList: [],
    customerId:{
      type: [Number,String],
      default: 0
    },
    historyDialog:Boolean,
    historyType:{
      type:String,
      default: 'SALE'
    }
  },
  components:{ Treeselect },
  data() {
    return {
      detailList: [],
      goodsBrandIds: [],
      goodsTypeIds: [],
      goodsId:0,
      query:{
        goodsKeyword:null,
        goodsBrandIds:null,
        goodsTypeIds:null,
        year: '',
        page:1,
        size:10
      },
      total:0,
      typeList: [],
      user: {},
      years:[],
      getHistoryFun:null
    }
  },
  updated() {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })},
  watch:{
    // customerId(n,o){
    //   this.query.page = 1
    //   this.getHistory()
    // },
    historyDialog(n){
      if (n){
        this.query.page = 1
        this.getHistory()
      }
    },
  },
  created() {
    this.getTypeList()
    this.getYear()
    this.user = this.$store.state.user.user

    if (this.historyType === 'SALE'){
      this.getHistoryFun = getSalesHistory
    }else{
      this.getHistoryFun = getBuyHistory
    }
    // this.getHistory();
  },
  methods: {
    currentcurrent(val){
      this.query.page = val
      this.getHistory()
    },
    onGoodsTypeNode(node){
      this.query.goodsTypeIds = this.getNode(node,'')
    },
    getHistory() {
      this.query.goodsBrandIds = this.goodsBrandIds.join(',')
      this.getHistoryFun({...this.query,customerId: this.customerId}).then(res => {
          this.detailList = res.data.content
          this.total = res.data.totalElements
        })
    },
    async getYear(){
      const data = {dictCode: 'dict_order_year',size: 999}
      const years = await getDict(data)
      // const year = new Date().getFullYear()
      this.years = years.content.filter(item=>item.value <= year)
      // this.query.year = year
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+','
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    getTypeList() {
      getTypeList({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    submitCU() {
      this.closedDialog()
      // this.$emit("change", this.resultGoods)
    },
    closedDialog() {
      this.$emit("update:showHistoryDialog", false)
    },

    sumAuxiliaryCount(boxNum,mainNum){
      let sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      for(let i in this.detailList){
        boxNumSum += Number(this.detailList[i][boxNum])
        mainNumsum += Number(this.detailList[i][mainNum])
      }
      return `${boxNumSum}箱${mainNumsum}瓶`
    },
    sumSelectAuxiliaryCount(boxNum,mainNum){
      let sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      for(let i in this.$refs.table.selection){
        boxNumSum += Number(this.detailList[i][boxNum])
        mainNumsum += Number(this.detailList[i][mainNum])
      }
      return `${boxNumSum}箱${mainNumsum}瓶`
    },
    sumRow(param) {
      const { columns, data } = param
      const sums = []
      const summaryList = ['boxCount', 'taxAmount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'count', 'noTaxAmount',
        'discountAmount', 'acceptBoxCount', 'acceptGoodsCount', 'acceptTaxAmount', 'acceptTax', 'cancelAmount', 'unCancelAmount', 'goodsCount',
        'checkGoodsCount', 'inAmount', 'balanceAmount', 'tax', 'acceptBoxNum', 'acceptMainNum', 'acceptNoTaxAmount', 'enterGoodsCount',
        'enterBoxCount', 'enterBoxNum', 'enterMainNum', 'enterTaxAmount', 'enterNoTaxAmount', 'enterTax', 'returnGoodsCount', 'returnBoxCount',
        'returnBoxNum', 'returnMainNum', 'returnTaxAmount', 'returnNoTaxAmount', 'returnTax', 'sendGoodsCount', 'sendBoxCount', 'sendBoxNum',
        'sendMainNum', 'sendTaxAmount', 'sendNoTaxAmount', 'sendTax', 'returnBottleBoxGoodsCount', 'returnBottleBoxBoxCount', 'returnBottleBoxBoxNum',
        'returnBottleBoxMainNum', 'returnBottleBoxTaxAmount', 'returnBottleBoxNoTaxAmount', 'returnBottleBoxTax', 'buyGoodsCount', 'buyBoxCount',
        'buyBoxNum', 'buyMainNum', 'buyTaxAmount', 'buyNoTaxAmount', 'buyTax', 'saleGoodsCount', 'saleBoxCount', 'saleBoxNum', 'saleMainNum',
        'saleTaxAmount', 'saleNoTaxAmount', 'saleTax', 'allotGoodsCount', 'form.allotBoxCount', 'allotBoxNum', 'allotMainNum', 'allotTaxAmount',
        'allotNoTaxAmount', 'allotTax', 'lossGoodsCount', 'lossBoxCount', 'lossBoxNum', 'lossMainNum', 'lossTaxAmount', 'lossNoTaxAmount', 'lossTax',
        'overGoodsCount', 'overBoxCount', 'overBoxNum', 'overMainNum', 'overTaxAmount', 'overNoTaxAmount', 'overTax', 'allotBoxCount', 'emptyBoxTaxAmount',
        'returnBoxTaxAmount', 'receiveAmount', 'receiptAmount', 'fuckNum', 'boxUnitId','existNum','usableNum','waitSendNum','expectUsableNum','pickNum'
      ]
      const auxiliaryList = ['boxNum', 'fuckNum','endBoxCount','inBoxNum','initBoxNum','outBoxNum','existBoxNum','usableBoxNum',
        'onWayBoxNum','pickBoxNum','waitSendBoxNum','allotOutBoxNum','allotInBoxNum']
      columns.forEach((column, index) => {
        let selectSum = 0
        if (index === 0) {
          sums[index] = <p>
            选中合计
            <hr />
            合计
          </p>
          column.colSpan = 2
          return
        }
        if (auxiliaryList.includes(column.property)) {
          let sum,selectSum
          switch (column.property){
            case 'boxNum':
              sum = this.sumAuxiliaryCount("boxNum",'mainNum')
              selectSum = this.sumSelectAuxiliaryCount('boxNum','mainNum')
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
            case 'fuckNum':
              sum = this.sumAuxiliaryCount('boxNum','mainNum')
              selectSum = this.sumSelectAuxiliaryCount('boxNum','mainNum')
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
            default:
              const name = column.property.split('BoxNum')[0]
              sum = this.sumAuxiliaryCount(`${name}BoxNum`,`${name}MainNum`)
              selectSum = this.sumSelectAuxiliaryCount(`${name}BoxNum`,`${name}MainNum`)
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
          }

        }
        if (this.$refs.table.selection.length > 0) {
          this.$refs.table.selection.map(sel => {
            for (const key in sel) {
              if (column.property === key) {
                if (summaryList.includes(key)) {
                  selectSum = (parseFloat(sel[key]) + (parseFloat(selectSum || 0))).toFixed(2)
                }
              }
            }
          })
        }
        if (summaryList.includes(column.property)) { // 指定哪一列合计 如果需要全部合计 去掉这个判断即可
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                const sum = prev + curr
                return sum
              } else {
                return prev
              }
            }, 0)
            sums[index - 1] = <p>{selectSum}<hr /> {sum.toFixed(2)}</p>
          } else {
            sums[index - 1] = ''
          }
        }
      })
      return sums
    },
  }
}
</script>

<style scoped>
.cu-footer{
  text-align: center;
  margin-top: 20px;
}
</style>
